'use strict';
angular.module("App")
    .controller('smsTabCtrl',['$scope','menu',function($scope,menu){
        //设置二级菜单
        $scope.subMenu = menu;

    }])
//获取短信列表
    .controller('smsListCtrl', ['$scope', '$http', '$location', '$log', 'smsService', function ($scope, $http, $location, $log, smsService) {

        $scope.smsData = [];
        $scope.maxSize = 3;
        $scope.totalItems = 0;
        $scope.rows = 5;
        $scope.smsList = {};
        $scope.choseArr = [];      //定义数组用于存放前端显示
        $scope.selected = false;   //默认未选中

        //全选
        $scope.selectAllClick = function (selectAll, smsData) {
            if (selectAll == true) {
                $scope.selected = true;
                $scope.choseArr = angular.copy(smsData);
            } else {
                $scope.selected = false;
                $scope.choseArr = [];
            }
            console.log($scope.choseArr);
        };
        //单选或者多选
        $scope.chk = function (ID, selected) {
            if (selected == true) {//选中
                $scope.choseArr.push(ID);
                if ($scope.choseArr.length == $scope.smsData.length) {
                    $scope.selectAll = true;
                }
            } else {
                $scope.choseArr.splice($scope.choseArr.indexOf(ID), 1);//取消选中
            }
            if ($scope.choseArr.length == 0) {
                $scope.selectAll = false
            }
            //console.log($scope.choseArr);
        };

        //批量删除操作
        $scope.deleteSelect = function () {
            // 操作CURD
            if ($scope.choseArr[0] == "" || $scope.choseArr.length == 0) {//没有选择一个的时候提示
                alert("请至少选中一条数据在操作！")
                return;
            }
            var arr = [];
            for (var i = 0; i < $scope.choseArr.length; i++) {
                arr.push($scope.choseArr[i]);
            }
            if (arr.length != 0) {

                smsService.batchDelete({
                    ID: arr.join("|")
                })
                    .then(function (data) {
                        if (!data.errCode) {
                            $location.path("#/sms/list");
                        }
                    });
            }
        }


        //页面改变时触发事件
        $scope.pageChanged = function () {

            smsService.getSms(
                {
                    Receiver: !$scope.smsList.person ? "" : $scope.smsList.person,
                    SendDate: !$scope.smsList.smsDate ? "" : $scope.smsList.smsDate,
                    SmsInfo: !$scope.smsList.queryVal ? "" : $scope.smsList.queryVal,
                    IsAchieved: !$scope.smsList.IsAchieved ? 2 : $scope.smsList.IsAchieved,   //2代表全部 0 代表未发送 1 代表已发送
                    page: $scope.currentPage,
                    rows: $scope.rows
                }
            ).then(function (data) {
                $scope.smsData = data.Sms_SendInfoList;
                $scope.totalItems = data.totalRows;
            }, function (error) {
                alert("Fail: " + error);
            })

        }


        //搜索
        $scope.search = function () {

            smsService.getSms(
                {
                    Receiver: !$scope.smsList.person ? "" : $scope.smsList.person,
                    SendDate: !$scope.smsList.smsDate ? "" : $scope.smsList.smsDate,
                    SmsInfo: !$scope.smsList.queryVal ? "" : $scope.smsList.queryVal,
                    IsAchieved: !$scope.smsList.IsAchieved ? 2 : $scope.smsList.IsAchieved,   //2代表全部 0 代表未发送 1 代表已发送
                    page: 1,
                    rows: $scope.rows
                }
            ).then(function (data) {
                $scope.currentPage = 1;
                $scope.smsData = data.Sms_SendInfoList;
                $scope.totalItems = data.totalRows;
            }, function (error) {
                alert("Fail: " + error);
            })
        }


        //页面初始化
        $scope.Inital = function () {
            smsService.getSms(
                {
                    Receiver: "",
                    SendDate: "",
                    SmsInfo: "",
                    IsAchieved: angular.isUndefined($scope.smsList.IsAchieved) ? 2 : $scope.smsList.IsAchieved,   //2代表全部 0 代表未发送 1 代表已发送
                    page: 1,
                    rows: $scope.rows
                }
            ).then(function (data) {
                $scope.smsData = data.Sms_SendInfoList;
                $scope.totalItems = data.totalRows;
            }, function (error) {
                alert("Fail: " + error);
            })
        }

        $scope.Inital();

        //删除数据
        $scope.removeSms = function (ev, id) {
            //阻止元素发生默认行为
            ev.preventDefault();
            smsService.deleteOne(
                {ID: id}
            ).then(function (data) {
                angular.forEach($scope.smsTemplate, function (val, key) {
                    if (id === val.SMS_MID) {
                        $scope.smsTemplate.splice(key, 1);
                        return;
                    }
                })
            }, function (error) {
                alert("Fail: " + error);
            })
        };
    }])
    //添加短信
    .controller('smsAddCtrl', ['$scope', '$http', '$location', 'utils', 'smsService', function ($scope, $http, $location, utils, smsService) {

        $scope.treeOptions = {
            nodeChildren: "children",
            dirSelectable: false,
            multiSelection: true,
            injectClasses: {
                ul: "a1",
                li: "a2",
                liSelected: "a7",
                iExpanded: "a3",
                iCollapsed: "a4",
                iLeaf: "a5",
                label: "a6",
                labelSelected: "a8"
            }
        }
        // $scope.selectedTemplate = "请选择模版";

        //获取短信模板
        smsService.getSmsTemplates(
        ).then(function (data) {
            $scope.selectedTemplates = data;
            $scope.selectedTemplate = $scope.selectedTemplates[0];
        }, function (error) {
            alert("Fail: " + error);
        })

        $scope.TemplateChange = function () {
            $scope.smsAdd.content = $scope.selectedTemplate.SMS_Mcont;
        }

        //获取通信录数据
        smsService.getSmsPhone(
        ).then(function (data) {
            $scope.dataForTheTree = data;
            $scope.dataForTheTree.state = false;
        }, function (error) {
            alert("Fail: " + error);
        })


        $scope.persons = [];
        $scope.smsAdd = {};
        var item = {};

        $scope.selectAll = function () {

        }


        $scope.showSelected = function (node, selected, $parentNode, $index) {

            //选中
            if (node.state) {
                //根节点
                if (node.children !== undefined) {

                    //根节点选中且包含元素
                    if (!angular.equals([], node.children)) {
                        angular.forEach(node.children, function (i) {
                            if (findIndex(i.UserID) == -1) {
                                item = {
                                    Username: i.UserName,
                                    UserID: i.UserID,
                                    Phone: i.Phone
                                }
                                $scope.persons.push(item);
                                i.state = true;
                            }

                        });
                    }
                }
                //元素
                else {

                    if (findIndex(node.UserID) == -1) {
                        item = {
                            Username: node.UserName,
                            UserID: node.UserID,
                            Phone: node.Phone
                        }
                        $scope.persons.push(item);
                        node.state = true;
                        $parentNode.state = true;
                    }
                    angular.forEach($parentNode.children, function (i) {
                        if (!i.state) {
                            $parentNode.state = false;
                            return;
                        }
                    });
                }

            }
            //未选中
            else {
                //取消根节点选中
                if (node.children !== undefined) {
                    //根节点选中且包含元素
                    if (!angular.equals([], node.children)) {
                        angular.forEach(node.children, function (i) {
                            var index = findIndex(i.UserID);
                            if (index != -1) {
                                $scope.persons.splice(index, 1);
                                i.state = false;
                            }
                        });
                    }
                }
                //取消元素选中
                else {
                    var index = findIndex(node.UserID);
                    if (index != -1) {
                        $scope.persons.splice(index, 1);
                        node.state = false;
                    }
                    $parentNode.state = false;
                }

            }
        };

        //发现选择项目
        var findIndex = function (UserID) {
            var index = -1;
            angular.forEach($scope.persons, function (item, key) {
                if (item.UserID == UserID) {
                    index = key;
                    return;
                }
            });
            return index;
        };

        $scope.submitForm = function () {

            var getNamePhone = function (_arr, Username, Phone) {
                var len = _arr.length;
                var tempArr = [];
                var res = "";
                for (var i = 0; i < len; i++) {
                    tempArr.push(_arr[i].Username + "," + _arr[i].Phone);
                }
                if (typeof(Username) != "undefined" && typeof(Phone) != "undefined") {
                    tempArr.push(Username + "," + Phone);
                }
                res = tempArr.join('|');
                return res;
            };

            //发送短信
            smsService.sendInfo(
                {
                    SmsInfo: $scope.smsAdd.content,
                    PhoneInfo: getNamePhone($scope.persons, $scope.Username, $scope.Phone)   //人员姓名，手机号 | 人员姓名，手机号
                }
            ).then(function (data) {
                $location.path("#/sms/list");
            }, function (error) {
                alert("Fail: " + error);
            })

        }

    }])

    //获取短信模版列表
    .controller('smsTemplateListCtrl', ['$scope', '$http', '$rootScope', '$state', 'common', 'smsService', function ($scope, $http, $rootScope, $state, common, smsService) {

        $scope.templateData = [];
        $scope.maxSize = 3;
        $scope.totalItems = 0;
        $scope.rows = 5;
        $scope.smsTemplate = {};

        //页面改变时触发事件
        $scope.pageChanged = function () {
            smsService.getSmstemplate(
                {
                    Mcont: $scope.smsTemplate.keyword,
                    page: $scope.currentPage,
                    rows: $scope.rows
                }
            ).then(function (res) {
                $scope.templateData = res.SMS_ModelList;
                $scope.totalItems = res.totalRows;
            }, function (error) {
                alert("Fail: " + error);
            })

        }


        //搜索
        $scope.search = function () {
            smsService.getSmstemplate(
                {
                    Mcont: $scope.smsTemplate.keyword,
                    page: 1,
                    rows: $scope.rows
                }
            ).then(function (res) {
                $scope.templateData = res.SMS_ModelList;
                $scope.totalItems = res.totalRows;
            }, function (error) {
                alert("Fail: " + error);
            })


        }


        //添加短信模版
        $scope.add = function (id) {
            smsService.addTemplate(
                {
                    SMS_MID: id,
                    Mcont: $scope.smsTemplate.Mcont
                }
            ).then(function (res) {
                $rootScope.tips.showSuccess("添加成功");
                $state.reload();
            }, function (error) {
                alert("Fail: " + error);
            })
        }

        //页面初始化
        $scope.Inital = function () {

            //获取短信模版
            smsService.getSmstemplate(
                {
                    Mcont: "",
                    page: 1,
                    rows: $scope.rows
                }
            ).then(function (res) {
                $scope.templateData = res.SMS_ModelList;
                $scope.totalItems = res.totalRows;
            }, function (error) {
                alert("Fail: " + error);
            })

        }

        $scope.Inital();

        //字段名加-代表倒排序
        //$scope.orderProp = "-SMS_MID";
        //删除数据
        $scope.removeTemplate = function (ev, id) {
            //阻止元素发生默认行为
            ev.preventDefault();
            $rootScope.showConfirm("确定要删除吗?").then(function () {
                //删除数据
                smsService.delTemplate(
                    {
                        ID: id
                    }
                ).then(function (res) {
                    $rootScope.tips.showSuccess("删除成功");
                    $state.reload();
                }, function (error) {
                    alert("Fail: " + error);
                })
            });

        };


        //编辑
        $scope.editTemplate = function (ev, id) {
            //阻止元素发生默认行为
            ev.preventDefault();
            //编辑数据
            smsService.editTemplate(
                {
                    ID: id
                }
            ).then(function (res) {
                $scope.smsTemplate.Mcont = res.SMS_Mcont;
                $scope.smsTemplate.Id = res.SMS_MID;
            }, function (error) {
                alert("Fail: " + error);
            })
        };

    }])
